// map.js
// 导入腾讯位置服务
import qqMap from '../../../utils/qqmap'
Page({
  data: {
    latitude: 0,
    longitude: 0,
    repairDetail: {},
    polyline: [],
    markers: [
      {
        id: 1,
        latitude: 22.55329,
        longitude: 113.88308,
        width: 20,
        height: 30,
      },
      {
        id: 2,
        latitude: 22.551898,
        longitude: 113.87986,
        iconPath: '/static/images/marker.png',
        width: 40,
        height: 40,
      },
    ],
  },
  onLoad({ id }) {
    // console.log(id)
    this.getRepairDetail(id)
    // 调用位置服务
    this.getPolyline()
  },
  // 报修详情接口
  async getRepairDetail(id) {
    if (!id) return wx.utils.toast('参数错误')
    // 调用接口
    const { code, data: repairDetail } = await wx.http.get('/repair/' + id)
    // 检测接口是否调用成功
    if (code !== 10000) return wx.utils.toast('获取报修详情失败')
    // 渲染数据
    this.setData({
      repairDetail,
    })
  },
  // 调用位置服务（路线规划）
  getPolyline() {
    qqMap.direction({
      mode: 'bicycling',
      // from: '113.88308,22.55329',
      // to: '113.87986,22.551898',
      from: this.data.markers[1],
      to: this.data.markers[0],
      success: ({ result }) => {
        console.log(result)
        const coors = result.routes[0].polyline
        const points = []
        // 坐标解压（返回点串坐标，通过前向差分进行压缩）
        for (let i = 2; i < coors.length; i++) {
          coors[i] = Number(coors[i - 2]) + Number(coors[i]) / 1000000
        }

        // 获取经纬度
        for (let i = 0; i < coors.length; i += 2) {
          points.push({
            latitude: coors[i],
            longitude: coors[i + 1],
          })
        }
        // console.log(points)
        // 渲染数据
        this.setData({
          latitude: points[0].latitude,
          longitude: points[0].longitude,
          polyline: [
            {
              points,
              color: '#5591af',
              width: 4,
            },
          ],
        })
      },
    })
  },
  // 修改报修信息
  editRepair(ev) {
    wx.navigateTo({
      url: '/repair_pkg/pages/form/index?id=' + ev.mark.id,
    })
  },
  // 取消报修
  async cancelRepair(ev) {
    // 调用接口·
    const { code } = await wx.http.put('/cancel/repaire/' + ev.mark.id)
    // 检测接口是否调用成功
    if (code !== 10000) return wx.utils.toast()
    // 跳转保报修列表页面
    wx.navigateTo({
      url: '/repair_pkg/pages/list/index',
    })
  },
})
